<?php
/*
* Description: base class for the models
*/
abstract class DbBase {

	//class variable
	var $table_name = null;	
	
	protected function execute($sql){
		return DbManager::execute($sql);
	}
	
	protected function query($sql){
		return DbManager::query($sql);
	}
	
	protected static function static_query($sql){
		return DbManager::query($sql);
	}
	
	public function find_by_id($user_id){
		$sql  = "SELECT * ";
		$sql .= " FROM ".$this->table_name;
		$sql .= " WHERE id=$user_id";
		
		$result = array_shift($this->query($sql));
		$this->construct_attributes($result);
	}
	
	public function set_attributes($data){
		
		$clean_data = array();
		$attrs = get_class_vars(get_class($this));
		unset($attrs['table_name']);
		
		foreach($attrs as $attr => $value)
			$clean_data[$attr] = $data[$attr];
		$this->construct_attributes($clean_data);
	}
	
	abstract function insert();
	abstract function update();
	abstract function delete();
	abstract function select();
	
	// PRIVATE METHODS section
	
	//set the attributes
	protected function construct_attributes($data){
		if(is_null($data) || empty($data))
			return;
			
		foreach($data as $key => $value){
			if(!is_numeric($key))
				$this->$key = $value;
		}
	}
	
	protected function validate($data = array()){
		if(empty($data)){
			$data = get_class_vars(get_class($this));
			unset($data['table_name']);
		}
		
		$error = '';
		foreach($data as $key => $value){
			if(is_null($this->$key) || $this->$key == ''){
				if(!is_null($value) || $value == '')
					$error .= " $value is empty <br>";
				else
					$error .= " $key is empty <br>";
			}
		}
		
		if($error != ''){
			throw new Exception($error);
		}
		
	}
}
?>